package com.though.soa;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.though.config.MessageConfig;
import com.though.config.Params;
import com.though.http.method.Get;
import com.though.http.soa.HttpInvoker;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CancellationException;

public class MessageInvoker {

	private static Logger logger = LoggerFactory.getLogger(MessageInvoker.class);
	
	protected final static String SIGN_NAME = "CC邀请码"; 
	protected final static String SIGN_NAME_SHOP_ORDER = "CC门店";

	protected final static String MOBILE_TEMPLATE_CODE = "SMS_42090037"; // 进货app手机登录邀请模板
	protected final static String SHOP_TEMPLATE_CODE = "SMS_105470051"; // 门店app手机登录邀请模板 

	protected final static String SHOP_ORDER_TEMPLATE_CODE ="SMS_100885176"; //  门店app手机开单短信通知


	protected final static String ERROR_KEY = "errorMessage"; // 返回错误的key

	public static Params params = new MessageConfig().getConfigParams();
	
	
	/**
	 * 发送验证码
	 */
	public static boolean sendGoodsLogin(String mobile, String number, String signName, String templateCode) {
		Get get = new Get(params.getHost() + "/singleSendSms");
		get.setParam("SignName", signName);
		get.setParam("TemplateCode", templateCode);
		get.setParam("RecNum", mobile);
		get.setParam("ParamString", number);
		
		get.setHeader("Authorization", "APPCODE " + params.getAppCode());
		
		String text = null;
		try {
			text = HttpInvoker.execute(get).getBody();
		} catch (Exception e) {
			logger.error("Invoker message is exception ", e);
			throw new CancellationException("短信接口调用异常！");
		}
		logger.warn("Message response {} mobile:{} number:{}", text, mobile, number);
		if (StringUtils.isBlank(text) || !text.startsWith("{")) throw new CancellationException("短信接口数据返回错误！");
		
		JSONObject json = JSON.parseObject(text);
		boolean success = json.getBooleanValue("success");
		if (!success) throw new CancellationException(json.getString("message"));
		return true;
	}
	
}